// pages/songDetail/songDetail.js
import PubSub from 'pubsub-js'
import Moment from 'moment'
import request from '../../utils/request.js';
// 获取全局实例
const appInstance = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        isPlay: false,
        song: {},
        musicId: '',
        musicLink: '', // 解决暂停重新播放重复发请求
        durationTime: '',
        currentTime: '00:00',
        currentWidth: ''
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        // console.log(options)
        let musicId = options.musicId
        // 路由传过来的参数，过长会被截掉
        // console.log(musicId)
        this.setData({
            musicId
        })
        this.getSongDetail(musicId)
        // 监听系统操作：开始暂停播放控制
        this.backgroundAudioManager = wx.getBackgroundAudioManager()
        this.backgroundAudioManager.onPlay(() => {
           this.systemControl(true)
           // 修改全局音乐播放状态
           appInstance.globalData.isMusicPlay = true
           appInstance.globalData.musicId = musicId
        })
        this.backgroundAudioManager.onPause(() => {
            this.systemControl(false)
        })
        this.backgroundAudioManager.onStop(() => {
            this.systemControl(false)
        })
        this.backgroundAudioManager.onWaiting(() => {
            this.systemControl(false)
        })
        this.backgroundAudioManager.onCanplay(() => {
            this.systemControl(true)
        })
        this.backgroundAudioManager.onEnded(() => {
            // this.systemControl(false)
            // 播放下一首、进度条更新
            PubSub.publish('switchType', 'next')
            this.setData({
                currentTime: '',
                currentWidth: 0,
            })
            PubSub.subscribe('musicId', (msg, musicId) => {
                // console.log(musicId)
                this.getSongDetail(musicId)
                // 下一首自动播放
                this.musicControl(true, musicId)
                // 取消订阅，解决执行多次
                PubSub.unsubscribe('musicId')
            })
        })
        // 监听播放进度
        this.backgroundAudioManager.onTimeUpdate(() => {
            // console.log(this.backgroundAudioManager.currentTime)
            const currentTime = Moment(this.backgroundAudioManager.currentTime*1000).format('mm:ss')
            const currentWidth = this.backgroundAudioManager.currentTime / this.backgroundAudioManager.duration * 450
            this.setData({
                currentTime,
                currentWidth
            })
        })
    },
    // 封装系统控制播放暂停
    systemControl(isPlay) {
        this.setData({
            isPlay
        })
    },
    // 播放按钮
    handleMusicPlay() {
        let isPlay = !this.data.isPlay
        this.setData({
            isPlay
        })
        let {musicId, musicLink} = this.data
        this.musicControl(isPlay, musicId, musicLink)
    },
    // 控制音乐播放
    async musicControl(isPlay, musicId, musicLink) {
        if(isPlay) { // 播放
            // 暂停后再次播放 不重复发请求
            if(!musicLink) {
                let musicSrc = await request('/song/url', {id: musicId})
                musicLink = musicSrc.data[0].url
                this.setData({
                    musicLink
                })
            }
            // 创建示例要前移
            this.backgroundAudioManager.src = musicLink
            this.backgroundAudioManager.title = this.data.song.name
        }else {// 暂停
            this.backgroundAudioManager.pause()
        }
    },
    // 获取音乐详情
    async getSongDetail(id) {
        const result = await request('/song/detail', {ids: id})
        let durationTime = Moment(result.songs[0].dt).format('mm:ss')
        this.setData({
            song: result.songs[0],
            durationTime
        })
        // 动态切换导航标题
        wx.setNavigationBarTitle({
          title: this.data.song.name,
        })
    },
    // 切换上下一首回调
    handleSwitch(event) {
        // console.log(event)
        // 关闭当前音乐
        this.backgroundAudioManager.stop()
         // 接收recommend回传的musicId
        PubSub.subscribe('musicId', (msg, musicId) => {
            // console.log(musicId)
            this.setData({
                musicId
            })
            this.getSongDetail(musicId)
            // 下一首自动播放
            this.musicControl(true, musicId)
            // 取消订阅，解决执行多次
            PubSub.unsubscribe('musicId')
        })
        let type = event.currentTarget.id
        // 发布消息给recommendSong
        PubSub.publish('switchType', type)
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})